package entity.thread.ticket;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TicketTest {


    public static void main(String[] args) {
        //synchronized控制抢票
//        TicketSystem ts = new TicketSystem();
//        new Thread(ts, "MrZhao").start();
//        new Thread(ts, "MrsDu").start();
//        new Thread(ts, "HuangNiu").start();

        //Lock锁控制抢票
        MyThread2 t1 = new MyThread2("Mrzhao");
        MyThread2 t2 = new MyThread2("MrsDu");
        MyThread2 t3 = new MyThread2("huangniu");
        t1.start();
        t2.start();
        t3.start();

    }


}

class TicketSystem implements Runnable {

    int num = 500;
    public boolean flag = true;

    @Override
    public void run() {

        while (flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void buy() throws InterruptedException {
        if (num < 1) {
            flag = false;
            return;
        }
        System.out.println(Thread.currentThread().getName() + "抢到了第" + num-- + "张票");
        Thread.sleep(10);

    }

}

class MyThread2 extends Thread {

    static Lock lock = new ReentrantLock();

    static int num = 500;

    public MyThread2(String mrzhao) {
        super(mrzhao);
    }

    public void run() {
        while (true) {
            lock.lock();
            try {
                if (num < 1) {
                    break;
                } else {
                    System.out.println(Thread.currentThread().getName() + "抢到了" + num);
                    num--;
                }
            } finally {
                lock.unlock();
            }


        }

    }

}
